var express = require('express');
var router = express.Router();

const {
    API_URL,
    suozi,
    getToken
} = require('../utils/config')
const Query = require('../utils/db')
const {
    v4: uuidv4
} = require('uuid');
const md5 = require('md5')


//登录
router.post('/api/login', async (req, res, next) => {
    let {
        username = '',
            password = '',
    } = req.body

    if (username == '' || password == '') {
        next({
            msg: '请传递必要参数',
        })
        return;
    }
    password = md5(password + suozi)

    let sql = `select mid from e_member where username = '${username}' and password = '${password}'`

    let {
        err,
        result
    } = await Query(sql);

    if (err) {
        next({
            msg: "请稍后再试",
        })
        return;
    }
    if (result.length == 0) {
        next({
            msg: "用户名或密码错误",
        })
        return;
    }

    let token = getToken({
        username,
        mid: result[0].mid
    })

    next({
        msg: "OK",
        status: 200,
        result: {
            token,
            mid: result[0].mid,
        }
    })
})

//注册
router.post('/api/register', async (req, res, next) => {
    let {
        username,
        password,
        repwd,
    } = req.body

    if (username == '' || password == '' || repwd == '') {
        next({
            msg: '请传递必要参数',
        })
        return;
    }

    if (password !== repwd) {
        next({
            msg: '两次密码不一致'
        })
        return;
    }

    let sql = `select mid from e_member where username = '${username}'`

    let {
        result
    } = await Query(sql);

    if (result.length != 0) {
        next({
            msg: "用户已被注册了",
        })
        return;
    }
    // return;
    if (username && !password || !repwd) {
        next({
            msg: "用户名可以使用"
        })
        return
    }

    let mid = uuidv4();;
    let createdate = Date.now();
    password = md5(password + suozi)

    let rSql = `insert into e_member (mid,username,password,createdate) values ('${mid}','${username}','${password}','${createdate}')`
    let {
        result: result1
    } = await Query(rSql);

    if (result1.affectedRows >= 1) {
        next({
            msg: "OK",
            status: 200,
        })
    }
    next({
        msg: "请稍后再试"
    })
})

module.exports = router;